package com.zHan.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zHan.model.dto.AssginRoleDto;
import com.zHan.model.dto.SysRoleQueryDto;
import com.zHan.model.system.SysRole;
import com.zHan.model.system.SysRoleMenu;
import com.zHan.model.system.SysUserRole;
import com.zHan.system.mapper.SysRoleMapper;
import com.zHan.system.mapper.SysRoleMenuMapper;
import com.zHan.system.mapper.SysUserRoleMapper;
import com.zHan.system.service.ISysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ClassName: SysRoleServiceImpl
 * Description:
 * date: 2023/6/19 0019 0:12
 *
 * @author zHan
 */
@Service
@Transactional
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService {

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private SysRoleMenuMapper roleMenuMapper;


    /**
     * 条件分页查询
     *
     * @param page
     * @param pageSize
     * @param roleQueryVo
     * @return
     */
    @Override
    public Page<SysRole> selectPageQuery(Long page, Long pageSize, SysRoleQueryDto roleQueryVo) {
        //初始化Page对象
        Page<SysRole> pageInfo = new Page<>(page, pageSize);
        //条件构造器
        LambdaQueryWrapper<SysRole> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //条件查询
        String roleName = roleQueryVo.getRoleName();
        String roleCode = roleQueryVo.getRoleCode();

        if (!StringUtils.isEmpty(roleName)) {
            lambdaQueryWrapper.like(SysRole::getRoleName, roleName);
        }

        if (!StringUtils.isEmpty(roleCode)) {
            lambdaQueryWrapper.like(SysRole::getRoleCode, roleCode);
        }
        lambdaQueryWrapper.orderByDesc(SysRole::getUpdateTime);
        //执行方法
        this.page(pageInfo, lambdaQueryWrapper);
        return pageInfo;
    }

    /**
     * 获取用户的角色数据
     *
     * @param userId
     * @return
     */
    @Override
    public Map<String, Object> selectRolesByUserId(String userId) {
        // 获取所有角色集合
        List<SysRole> roles = roleMapper.selectList(null);

        // 获取userId对应的角色
        LambdaQueryWrapper<SysUserRole> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysUserRole::getUserId, userId);
        List<SysUserRole> userRoleList = userRoleMapper.selectList(lambdaQueryWrapper);

        // 获得所有的角色id
        List<String> roleIds = new ArrayList<>();
        for (SysUserRole userRole : userRoleList) {
            roleIds.add(userRole.getRoleId());
        }
        // 返回map集合
        Map<String, Object> map = new HashMap<>();
        map.put("allRoles", roles);
        map.put("userRoleIds", roleIds);

        return map;
    }

    /**
     * 给用户分配角色
     *
     * @param assginRoleDto
     * @return
     */
    @Override
    @Transactional
    public boolean assignRoleToUser(AssginRoleDto assginRoleDto) {
        // 根据userId删除已分配的角色
        LambdaQueryWrapper<SysUserRole> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysUserRole::getUserId, assginRoleDto.getUserId());
        userRoleMapper.delete(lambdaQueryWrapper);

        // 获取所有角色id，添加到用户角色关系表
        List<String> roleIdList = assginRoleDto.getRoleIdList();
        for (String roleId : roleIdList) {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setUserId(assginRoleDto.getUserId());
            sysUserRole.setRoleId(roleId);
            userRoleMapper.insert(sysUserRole);
        }

        return true;
    }

    /**
     * 删除角色
     *
     * @param id
     * @return
     */
    @Override
    public boolean removeRoleById(Long id) {
        try {
            //先删除用户表中的信息
            this.removeById(id);
            //再删除其他表中的数据
            userRoleMapper.delete(Wrappers.<SysUserRole>lambdaQuery()
                    .eq(SysUserRole::getRoleId, id));
            roleMenuMapper.delete(Wrappers.<SysRoleMenu>lambdaQuery()
                    .eq(SysRoleMenu::getRoleId, id));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return true;
    }

    /**
     * 批量删除角色
     *
     * @param idList
     * @return
     */
    @Override
    public boolean removeRoleByIds(List<Long> idList) {
        try {
            //先删除用户表中的信息
            this.removeByIds(idList);
            //再删除其他表中的数据
            userRoleMapper.delete(Wrappers.<SysUserRole>lambdaQuery()
                    .in(SysUserRole::getRoleId, idList));
            roleMenuMapper.delete(Wrappers.<SysRoleMenu>lambdaQuery()
                    .in(SysRoleMenu::getRoleId, idList));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return true;
    }
}
